import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../../util/response-util";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../../util/page-subject";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../../../models/msg-result";
import {API, MsgConstants} from "../../../../../constants/constants";
import {TreeUtil} from "../../../../../util/tree-util";
import {RetrieveRegionsService} from "../../channel/regions-add.service";
import {DataStorageUtil} from "../../../../../util/data-storage-util";
import {Receiver} from "../../channel/receiver";

declare var $;

@Component({
  selector: 'app-instance-assign-receiver',
  templateUrl: './instance-assign-receiver.component.html'
})
export class InstanceAssignReceiverComponent implements OnInit {

  table;
  treeObj;
  Node;

  // receiver: Receiver;

  receivers: Array<any> = [];

  regionCode: string;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private treeUtil: TreeUtil,
              private responseUtil: ResponseUtil,
              private dialogService: OneDialogService,
              private dataStorageUtil: DataStorageUtil,
              private retrieveRegionsService: RetrieveRegionsService,) {
  }

  ngOnInit() {
    this.pushPage();
    this.getRegionTree();
  }

  /**
   * 面包屑
   */
  private pushPage() {
    let path = new Path("报警管理", "");
    this.pageSubject.pushPage("实例管理", "选择发送人", path);
  }

  /**
   * 初始化已选数据
   */

  initTree(init) {
    var array = new Array();
    array = init.split(",");
    var treeObj = $.fn.zTree.getZTreeObj("orgTree");
    var nodes = treeObj.getNodes();
    var nodesArray = treeObj.transformToArray(nodes);

    if (!!init) {
      array.forEach(function (value) {
        if (!!value) {
          nodesArray.forEach(function (node) {
            if (value.split("|")[0] == node.id) {
              node.checked = true;
              treeObj.updateNode(node);
              let receiver = new Receiver(node.id, node.name, node.type, node);
              this.receivers.push(receiver);
              return;
            }
          }, this);
        }
      }, this);
    }


  }

  /**
   * 获取行政区划树
   */
  getRegionTree() {
    let regionCode = "0";
    this.retrieveRegionsService.getRegionsTreeByRegionCode(regionCode).subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //console.log("------" + JSON.stringify(result.data));
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  行政区划树
   */
  private regioCodezTree(datasTree) {
    let datas = datasTree || [];
    // 新增中的树
    let userUpdateZtreeSetting = {
      check: {
        enable: true,
        chkboxType: {"Y": "", "N": ""}
        // chkboxType :{ "Y" : "s", "N" : "s" }

      },
      callback: {
        onCheck: this.zTreeOnCheck
      },
      view: {
        fontCss: this.setFontCss_ztree, //设置字体颜色
        dblClickExpand: true,
        selectedMulti: true
      },
    };

    $.fn.zTree.init($("#orgTree"), userUpdateZtreeSetting, datas);
    if (!!this.route.snapshot.params["initReceiver"]) {
      this.initTree(this.route.snapshot.params["initReceiver"]);
    }
  }

  /**
   * 设置树节点字体样式
   */
  private setFontCss_ztree(treeId, treeNode) {
    if (treeNode.id == 0) {
      //根节点
      return {color: "#333", "font-weight": "bold"};
    } else if (treeNode.isParent == false) {
      //叶子节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    } else {
      //父节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    }
  }

  /**
   * 搜索节点，并展开
   */
  enterSearch() {
    let inputValue = $("#serach_regionName").val();
    let treeId = "orgTree";
    this.treeUtil.searchTreeNode(treeId, inputValue);
  }

  /**
   * 处理树复选框选中事件
   */
  zTreeOnCheck = (event, treeId, treeNode) => {
    // console.log(treeNode);
    //选中状态
    if (treeNode.checked) {
      let receiver = new Receiver(treeNode.id, treeNode.name, treeNode.type, treeNode);
      this.receivers.push(receiver);
      //未选中
    } else {
      this.receivers.forEach(function (value, index, array) {
        if (treeNode.id == value.id) {
          this.receivers.splice(index, 1);
        }
      }, this);
    }
  };


  deleteReceiver(receiver) {
    this.receivers.forEach(function (value, index, array) {
      if (receiver.id == value.id) {
        this.receivers.splice(index, 1);
        var zTree = $.fn.zTree.getZTreeObj("orgTree");
        value.treeNode.checked = false;
        zTree.updateNode(value.treeNode);
      }
    }, this);
  }


  /**
   * 取消选取，
   * 1.如果修改页面选取发送人，则传入一个路由id；
   * 2.判断路由id是否为空，为空跳到添加页面；
   * 3.否则跳到修改页面
   */
  cancel() {
    let isGroup = this.route.snapshot.params['isGroup'];
    if (!!this.route.snapshot.params['id']) {
      let id = this.route.snapshot.params['id'];
      this.router.navigate(['../update', {id: id ,isGroup:isGroup}], {relativeTo: this.route});
    } else {
      this.router.navigate(['../add', {isGroup:isGroup}], {relativeTo: this.route});
    }
  }

  /**
   * 保存选取的发送人
   * 1.如果路由id不为空，跳到修改页面，
   * 2.否则跳到添加页面
   */
  save() {
    this.dataStorageUtil.set("receiver", JSON.stringify(this.receivers));
    let isGroup = this.route.snapshot.params['isGroup'];
    if (!!this.route.snapshot.params['id']) {
      let id = this.route.snapshot.params['id'];
      this.router.navigate(['../update', {id: id,tag: "tag" ,isGroup:isGroup}], {relativeTo: this.route});
    } else {
      this.router.navigate(['../add', {tag: "tag",isGroup:isGroup}], {relativeTo: this.route});
    }

  }

}
